package org.phalanx.map;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import org.phalanx.map.xml.TileSetXMLFileHandler;
import org.phalanx.zip.ZipFileArchiveReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class PhalanxTileSetReader {
	private ZipFileArchiveReader terrainFile;
	private MapTileSet tileSet = new MapTileSet();
	private String archiveFile;
	
	public static final String TILE_XML_FILENAME = "tileset.xml";
	
	public PhalanxTileSetReader(){}
	
	public PhalanxTileSetReader(ZipFileArchiveReader z){
		terrainFile = z;
	}
	
	public void setTerrainFile(File newMapFile) throws IOException{
		terrainFile = new ZipFileArchiveReader(newMapFile);
	}
	
	public void setTerrainFileByName(String newMapFileName) throws IOException{
		terrainFile = new ZipFileArchiveReader(newMapFileName);
	}
	
	public ZipFileArchiveReader getArchiveReader(){
		return terrainFile;
	}
	
	public boolean readInTerrain(){
		boolean isSuccess = false;
		
		try {
			
			String xmlData = terrainFile.getArchivedFileAsString(TILE_XML_FILENAME);
			
			if (xmlData != null){
				XMLReader tileSetParser= XMLReaderFactory.createXMLReader();

				TileSetXMLFileHandler tileHandler = new TileSetXMLFileHandler(tileSet);
				tileSetParser.setContentHandler(tileHandler);
/*				tileSetParser.parse(xmlData);*/
				tileSetParser.parse(new InputSource(new StringReader(xmlData)));
				
				isSuccess = true;
			}
		} catch (SAXException sax){ sax.printStackTrace();} catch (IOException ie){ ie.printStackTrace();}
		return isSuccess;
	}
	
	public MapTileSet getMapTileSet(){
		return this.tileSet;
	}
	
	public static void main(String[] args) {
		PhalanxTileSetReader p = new PhalanxTileSetReader();
		try {
			p.setTerrainFileByName("/home/sday/phalanxArt/DefaultTileSet.zip");
			p.readInTerrain();
		} catch (IOException ie){}
	}
	
}
